package controllers

import (
	"net/http"

	"gitee.com/golanglearn/small/app"
	"gitee.com/golanglearn/small/models"
	"gitee.com/golanglearn/small/repositories"
	"gitee.com/golanglearn/small/services"
	"gitee.com/golanglearn/small/wx"
	"github.com/gorilla/mux"
	"log"
)

type WxController struct {
	*app.App
	repositories.UserRepository
	jwtService services.JWTAuthService
}

func NewWxController(a *app.App, ur repositories.UserRepository, jwtService services.JWTAuthService) *WxController {
	return &WxController{a, ur, jwtService}
}

func (wc *WxController) WxLogin(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)

	//获取openid
	wxn := wx.NewWx(appid, secret)
	ws, err := wxn.GetWxSessionKey(vars["code"])
	if err != nil {
		log.Println(err)
		NewAPIError(&APIError{false, "Could not get openid", http.StatusBadRequest}, w)
		return
	}

	if ws.Openid == "" {
		log.Println(ws)
		NewAPIError(&APIError{false, "Could not get openid", http.StatusBadRequest}, w)
		return
	}

	u, err := wc.UserRepository.FindByOpenId(ws.Openid)
	if err != nil {
		// user was not found
		NewAPIError(&APIError{false, "Could not find user", http.StatusNotFound}, w)
		return
	}

	tokens, err := wc.jwtService.GenerateTokens(u)
	if err != nil {
		NewAPIError(&APIError{false, "Something went wrong", http.StatusBadRequest}, w)
		return
	}

	authUser := &models.AuthUser{
		User:  u,
		Admin: u.Admin,
	}

	data := struct {
		Tokens *services.Tokens `json:"tokens"`
		User   *models.AuthUser `json:"user"`
	}{
		tokens,
		authUser,
	}

	defer r.Body.Close()
	NewAPIResponse(&APIResponse{Success: true, Message: "Login successful", Data: data}, w, http.StatusOK)
}
